package com.zuijin.vue2blog.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zuijin.vue2blog.common.api.Result;
import com.zuijin.vue2blog.common.utils.JwtUtil;
import com.zuijin.vue2blog.dto.UserComParam;
import com.zuijin.vue2blog.entity.UserCom;
import com.zuijin.vue2blog.service.UserComService;
import io.swagger.annotations.ApiOperation;
import org.apache.el.parser.Token;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import io.swagger.annotations.Api;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;


/**
 * <p>
 * 普通用户表 前端控制器
 * </p>
 *
 * @author 醉瑾
 * @since 2022-04-22
 */
@Api(tags = "普通用户表")
@RestController // https://blog.csdn.net/qq_41192218/article/details/113354167
@RequestMapping("/user/com")
public class UserComController {
    @Resource
    private UserComService userComService;

    @Resource
    private JwtUtil jwtUtil;

    @Value("${jwt.tokenHeader}")
    private String tokenHeader;

    @Value("${jwt.tokenHead}")
    private String tokenHead;

    @ApiOperation(value = "用户注册")
    @PostMapping("/register")
    public Result<UserCom> register(@Validated @RequestBody UserComParam userComParam) {
        UserCom userCom = userComService.register(userComParam);
        if (userCom == null) {
            return Result.ERROR("注册失败");
        }
        return Result.OK(userCom);
    }

    @ApiOperation(value = "进行登录操作，并返回token")
    @PostMapping("/login")
    public Result<Map<String, String>> login(@Validated @RequestBody UserComParam userComParam) {
        String token = userComService.login(userComParam);
        if (token == null) {
            return Result.validateFailed("用户名或密码错误");
        }
        Map<String, String> tokenMap = new HashMap<>() {{
            put("token", token);
            // put("tokenHead", tokenHead);
        }};
        return Result.OK(tokenMap);
    }

    @ApiOperation(value = "获取用户信息")
    @PostMapping("/getUserInfo/{id}")
    public Result<UserCom> getUserInfo(@PathVariable("id") Integer id) {
        UserCom userCom = userComService.getById(id);
        return Result.OK(userCom);
    }

    @ApiOperation(value = "修改用户信息")
    @PutMapping("/update")
    public Result<Map<String, Object>> update(@Validated @RequestBody UserComParam userComParam) {
        UserCom userCom = new UserCom();
        BeanUtils.copyProperties(userComParam, userCom);
        boolean b = userComService.updateById(userCom);
        if (!b) {
            return Result.ERROR("用户信息修改失败");
        }
        Map<String, Object> update = new HashMap<>() {{
            put("token", userComService.login(userComParam));
            put("newUser", userCom);
        }};
        return Result.OK(update);
    }
}
